package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.iwhalecloud.citybrain.flow.platform.manager.application.event.EventCallURL;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCompletedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.eventconfig.DeployedEventConfigDomain;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.eventconfig.EventMethodEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import com.netflix.hystrix.HystrixCommand;
/**
 * @author lilh
 * @date 2021/2/26 13:33
 */
@Slf4j
@Component
@Order(1)
public class SendBusinessSystemAfterTaskCompletedProcessor implements TaskCompletedPostProcessor {

    @Autowired
    private CommonTaskEventProcessor commonTaskEventProcessor;

    @Override
    public void process(TaskEntity taskEntity) throws EventCallSuspendException {
        log.info("任务后置事件, processDefinitionId=>{}, taskId=>{} ", taskEntity.getProcessDefinitionId(), taskEntity.getId());
        //1.根据任务信息，查询关联的配置信息
        List<DeployedEventConfigDomain> eventConfigs = commonTaskEventProcessor.resolveEventConfigList(
                taskEntity, FlowableEngineEventType.TASK_COMPLETED.name());
        if (Objects.isNull(eventConfigs)) {
            log.info("当前任务没有后置url，不需要执行");
            return;
        }
        // 对每条记录都执行一次
        for (DeployedEventConfigDomain config: eventConfigs) {
            String types = config.getCallbackType();
            switch (EventMethodEnum.queryEnum(types)) {
                case HTTP_URL:
                    new EventCallURL(taskEntity
                            , config
                    ).doProcess("任务后置");
                    break;
                case GROOVY:
                    // TODO
                    break;
                case JAVA_CLASS:
                    // TODO
                    break;
                default:
                    log.error("不支持的触发类型");
                    break;
            }
        }
    }

    @Override
    public String getDesc() {
        return "任务完成时调用第三方系统";
    }

}
